package com.lzwork.gpt.jobs;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.alibaba.fastjson.JSONObject;
import com.lzwork.gpt.utility.caller.GptCallResult;
import com.lzwork.gpt.utility.common.ParserCaller;
import com.lzwork.utility.TimeTicker;
import com.lzwork.utility.data.NumberParse;
import com.lzwork.utility.file.FileUtility;
import com.lzwork.utility.officeparser.ExcelLoader;
import com.lzwork.utility.officeparser.ExcelReader;
import com.lzwork.utility.officeparser.ExcelReader.ColumnIndex;
import com.lzwork.utility.officeparser.ExcelSaver;
import com.lzwork.utility.pair.StringPair;
import com.lzwork.utility.str.StrUtility;

/**
 * @author LiZheng
 * @date 2023年12月26日 14:17:05
 */

public class BatchExcelCaller extends ExcelSaver
{
	public BatchExcelCaller(String fullUrl, List<StringPair> keyToColumn)
	{
		this.keyToColumn = keyToColumn;
		caller = new ParserCaller(fullUrl, false);
	}

	final static String[] removePerfix =
	{ "事件描述：", "市民投诉", "市民反映", "市民举报", "投诉：", "诉求：", "市民抱怨" };

	ParserCaller caller;
	List<StringPair> keyToColumn;

	final static String STATE_KEY = "State";
	int stateVer = 1;

	protected String prefixCheck(String text)
	{
		for (String p : removePerfix)
		{
			if (text.startsWith(p))
				text = text.substring(p.length());
		}
		return text;
	}

	protected String poseProcess(String input)
	{
		String str = input;
		if (str.endsWith("。"))
		{
			str = str.substring(0, str.length() - 1);
		}

		int index = str.lastIndexOf('。');
		if (index > 0)
		{
			str = str.substring(0, index);
			return str;
		}

		index = str.lastIndexOf('，');
		if (index > 0)
		{
			str = str.substring(0, index);
			return str;
		}

		return input;
	}

	protected List<StringPair> getParam(Row row, ColumnIndex keyColumnMap)
	{
		List<StringPair> result = new ArrayList<>();

		for (StringPair sp : keyToColumn)
		{
			String paramKey = sp.first();
			String colKey = sp.second();

			int index = keyColumnMap.getFieldAt(colKey);
			String data = ExcelLoader.getCellData(row, index).getString();

			result.add(new StringPair(paramKey, data));
		}

		return result;
	}

	public void doExcelCall(File file, String outputField, boolean refresh, boolean dolog, int tempSave)
	{
		Workbook wb = ExcelLoader.loadWorkBook(file);
		TimeTicker ticker = new TimeTicker();
		int totalWrite = 0;

		for (Sheet sheet : wb)
		{
			Row head = sheet.getRow(0);
			ColumnIndex keyColumnMap = ExcelReader.readFieldIndex(sheet, 0);

			int outIndex = keyColumnMap.getFieldAt(outputField);
			int stateIndex = keyColumnMap.getFieldAt(STATE_KEY);

			if (outIndex < 0)
			{
				Cell cell = appendCell(head, outputField);
				outIndex = cell.getColumnIndex();
			}

			if (stateIndex < 0)
			{
				Cell cell = appendCell(head, STATE_KEY);
				stateIndex = cell.getColumnIndex();
			}

			System.out.println(
					"Sheet [" + sheet.getSheetName() + "]. Result index: " + outIndex + ", state index: " + stateIndex);

			int num = 0;
			int skip = 0;
			for (Row row : sheet)
			{
				num++;
				if (num > 0 && num % 10 == 0)
					System.out.println("Sheet [" + sheet.getSheetName() + "]: " + num + " items checked. Skip: " + skip);

				if (tempSave > 0 && tempSave <= totalWrite && totalWrite % tempSave == 0)
				{
					File temp = FileUtility.renameFileSafe(file, "_temp", true);
					System.out.println("Save temp file at total write: " + totalWrite);
					saveXlsFile(wb, temp);
				}

				Cell resultCell = pickCellAt(row, outIndex);
				Cell stateCell = pickCellAt(row, stateIndex);

				if (!refresh)
				{
					String content = ExcelLoader.getCellData(row, outIndex).getString();
					if (StrUtility.stringValid(content))
					{
						String change = prefixCheck(content);

						int state = NumberParse.objToInt(ExcelLoader.getCellData(stateCell).getString(), -1);

						if (state < stateVer)
						{
							change = poseProcess(change);
							stateCell.setCellValue(stateVer);
						}

						if (!change.equals(content))
						{
							resultCell.setCellValue(change);
						}

						skip++;
						continue;
					}
				}

				List<StringPair> params = getParam(row, keyColumnMap);

				JSONObject param = new JSONObject(true);
				for (StringPair sp : params)
				{
					param.put(sp.first(), sp.second());
				}
				param.put("dolog", dolog);

				GptCallResult cr = caller.call(param);

				JSONObject errObj = cr.getError();
				if (errObj != null)
					continue;

				String response = cr.getResponse();
				response = prefixCheck(response);
				response = poseProcess(response);

				resultCell.setCellValue(response);
				stateCell.setCellValue(stateVer);
				totalWrite++;
			}

			System.out.println("Sheet [" + sheet.getSheetName() + "] done. Cost " + ticker.tickS());
		}

		System.out.println("All done. Cost " + ticker.tickAllS());
		saveXlsFile(wb, file);
	}

	public static void main(String[] args)
	{
		String api = "http://127.0.0.1:8083/job/callapi?apikey=204xfy1zgxir7z6zkrlp6vewc";

		List<StringPair> param = new ArrayList<>();

		param.add(new StringPair("{{event}}", "诉求内容"));

		BatchExcelCaller caller = new BatchExcelCaller(api, param);

		File file = new File("v:/12345/智能派单202309_总_in4-ver2.xlsx");

		caller.doExcelCall(file, "Event", false, false, 50);
	}
}
